package org.example.demo1.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.demo1.Entity.ApiResponse;
import org.example.demo1.Entity.ClusterInfo;
import org.example.demo1.service.ClusterService;
import org.example.demo1.service.ServiceDiscoveryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/navigate")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class NavigatorController {
    private final ClusterService clusterService;
    private final ServiceDiscoveryService serviceDiscoveryService;

    @GetMapping("/cluster/status")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getClusterStatus() {
        try {
            boolean connected = clusterService.isConnected();
            return ResponseEntity.ok(ApiResponse.success(Map.of("connected", connected)));
        } catch (Exception e) {
            log.error("检查集群状态失败", e);
            return ResponseEntity.ok(ApiResponse.success(Map.of("connected", false)));
        }
    }

    @GetMapping("/cluster/info")
    public ResponseEntity<ApiResponse<ClusterInfo>> getClusterInfo() {
        try {
            ClusterInfo clusterInfo = clusterService.getClusterInfo();
            return ResponseEntity.ok(ApiResponse.success(clusterInfo));
        } catch (Exception e) {
            log.error("获取集群信息失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取集群信息失败: " + e.getMessage()));
        }
    }

    @GetMapping("/services/discover")
    public ResponseEntity<ApiResponse<Map<String, Object>>> discoverServices() {
        try {
            Map<String, Object> services = serviceDiscoveryService.discoverMonitoringServices();
            return ResponseEntity.ok(ApiResponse.success(services));
        } catch (Exception e) {
            log.error("服务发现失败", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("服务发现失败: " + e.getMessage()));
        }
    }

    @GetMapping("/health")
    public ResponseEntity<ApiResponse<Map<String, Object>>> healthCheck() {
        return ResponseEntity.ok(ApiResponse.success(Map.of(
                "status", "healthy",
                "cluster_connected", clusterService.isConnected()
        )));
    }
}
